package com.vertx.data.utils;

import io.vertx.core.AsyncResult;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.jdbc.JDBCClient;
import io.vertx.redis.RedisClient;
import io.vertx.redis.RedisOptions;
import org.apache.log4j.Logger;

/***
 * DB链接工具类
 */
public class DbUtils {
    private static JDBCClient client = null;

    private static RedisClient redisClient=null;

    private  final Logger logger = Logger.getLogger(DbUtils.class);


    private int initJDBC(Vertx vertx, JsonObject config) {
        if (client == null) {
            synchronized (DbUtils.class) {
                if (client == null) {
                    // 根据配置信息创建JDBC连接客服端
                    JsonObject jdbcConfig = new JsonObject()
                            .put("url", config.getString("url"))
                            .put("provider_class",config.getString("provider_class"))
                            .put("driver_class", config.getString("driver_class"))
                            .put("user", config.getString("user"))
                            .put("password", config.getString("password"))
                            .put("dataPackage",config.getString("dataPackage"));
                    client = JDBCClient.createShared(vertx, jdbcConfig);
                }else{
                    logger.error("client is not null");
                }
            }
        }
        return 0;
    }

    private int initRedis(Vertx vertx,JsonObject config){
        if(redisClient == null){
            synchronized (DbUtils.class){
                if(redisClient==null){
                    // 读取配置加载Redis所需配置信息
                    if(config.getBoolean("redis.open")){
                        RedisOptions redisOptions=new RedisOptions();
                        redisOptions.setHost(config.getString("redis.host"));
                        redisOptions.setPort(config.getInteger("redis.port"));
                        redisOptions.setAuth(config.getString("redis.auth"));
                        redisClient=RedisClient.create(vertx,redisOptions);
                    }
                }
            }
        }
        return 0;
    }

    /***
     * 提供对外jdbc
     * @return
     */
    public static JDBCClient getJdbcClient() {
        return client;
    }

    /***
     * 异步方式初始连接
     *
     * @param vertx
     * @param config
     * @return
     */
    public void initJdbcAsync(Vertx vertx, JsonObject config, Handler<AsyncResult<Integer>> handler){
        handler.handle(Future.succeededFuture(this.initJDBC(vertx, config)));
    }

    public void initRedisAsync(Vertx vertx,JsonObject config,Handler<AsyncResult<Integer>> handler){
        handler.handle(Future.succeededFuture(this.initRedis(vertx,config)));
    }
}
